package org.dant.ant.extension.tasks;

import java.util.List;

import org.apache.tools.ant.Task;

import org.dant.ant.extension.tasks.internal.Endpoint;
import org.dant.ant.extension.tasks.internal.RemoteResponse;
import org.dant.ant.extension.tasks.internal.RemoteCommand;

public class CommandSender implements Runnable {

  Endpoint endpoint;

  Thread cmdSendThread;
  RemoteResponse response;
  RemoteCommand request;
  boolean transmit = true;
  
  public CommandSender() {}

  public void setTransmit(boolean transmit) {
    this.transmit = transmit;
  }

  public void setRemoteCommand(RemoteCommand request) {
    this.request = request;
  }

  public void setEndpoint(Endpoint endpoint) {
    this.endpoint = endpoint;
  }

  public RemoteResponse getResponse() {
    return this.response;
  }

  public Thread getThread() {
    return this.cmdSendThread;
  }

  public void start() {
    cmdSendThread = new Thread(this);
    cmdSendThread.start();
  }

  public void run() {
    try {
      if (transmit) {
        response = endpoint.getRemoteHelper().invoke(endpoint, request);
      } else {
        response = new RemoteResponse();
        response.setResult("The command is not transmitted to the remote host [" + endpoint + "] , print the command");
        response.appendResult(request.toString());
      }
      response.setTaskName((String)request.getParameters().get("taskname"));
    } catch (Exception e) {
      e.printStackTrace();
      response.setSuccess(false);
      response.setResult(e.getMessage());
    }
  }
}
